/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Bhaskara;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author Rafael
 */
public class BhaskaraMIDlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private Command backCommand;
    private Command CalcularCommand;
    private Command IrCommand;
    private Command ProxCommand;
    private Command helpCommand;
    private Form Principalform;
    private TextField valorBtextField;
    private TextField valorAtextField;
    private TextField valorCtextField;
    private StringItem resultadoStringItem;
    private Form Logo;
    private ImageItem imageItem1;
    private Form Descricaoform;
    private StringItem stringItem;
    private Image Bháskara;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The HelloMIDlet constructor.
     */
    public BhaskaraMIDlet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|
    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
        Principalform = new Form("C\u00E1lculo do Bhaskara", new Item[] { getValorAtextField(), getValorBtextField(), getValorCtextField(), getResultadoStringItem() });//GEN-BEGIN:|0-initialize|1|0-postInitialize
        Principalform.addCommand(getExitCommand());
        Principalform.addCommand(getBackCommand());
        Principalform.addCommand(getCalcularCommand());
        Principalform.setCommandListener(this);//GEN-END:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getLogo());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == Descricaoform) {//GEN-BEGIN:|7-commandAction|1|52-preAction
            if (command == ProxCommand) {//GEN-END:|7-commandAction|1|52-preAction
                // write pre-action user code here
                switchDisplayable(null, Principalform);//GEN-LINE:|7-commandAction|2|52-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|39-preAction
        } else if (displayable == Logo) {
            if (command == IrCommand) {//GEN-END:|7-commandAction|3|39-preAction
                // write pre-action user code here
                switchDisplayable(null, getDescricaoform());//GEN-LINE:|7-commandAction|4|39-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|5|30-preAction
        } else if (displayable == Principalform) {
            if (command == CalcularCommand) {//GEN-END:|7-commandAction|5|30-preAction
                getResultado();
//GEN-LINE:|7-commandAction|6|30-postAction
                // write post-action user code here
            } else if (command == backCommand) {//GEN-LINE:|7-commandAction|7|23-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|8|23-postAction
                // write post-action user code here
            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|9|19-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|10|19-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|11|7-postCommandAction
        }//GEN-END:|7-commandAction|11|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|12|
    //</editor-fold>//GEN-END:|7-commandAction|12|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|18-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            backCommand = new Command("Finalizar", Command.BACK, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|22-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: valorAtextField ">//GEN-BEGIN:|24-getter|0|24-preInit
    /**
     * Returns an initiliazed instance of valorAtextField component.
     * @return the initialized component instance
     */
    public TextField getValorAtextField() {
        if (valorAtextField == null) {//GEN-END:|24-getter|0|24-preInit
            // write pre-init user code here
            valorAtextField = new TextField("Digite o valor de A:", "", 32, TextField.ANY);//GEN-LINE:|24-getter|1|24-postInit
            // write post-init user code here
        }//GEN-BEGIN:|24-getter|2|
        return valorAtextField;
    }
    //</editor-fold>//GEN-END:|24-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: valorBtextField ">//GEN-BEGIN:|25-getter|0|25-preInit
    /**
     * Returns an initiliazed instance of valorBtextField component.
     * @return the initialized component instance
     */
    public TextField getValorBtextField() {
        if (valorBtextField == null) {//GEN-END:|25-getter|0|25-preInit
            // write pre-init user code here
            valorBtextField = new TextField("Digite o valor de B:", "", 32, TextField.ANY);//GEN-LINE:|25-getter|1|25-postInit
            // write post-init user code here
        }//GEN-BEGIN:|25-getter|2|
        return valorBtextField;
    }
    //</editor-fold>//GEN-END:|25-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: valorCtextField ">//GEN-BEGIN:|26-getter|0|26-preInit
    /**
     * Returns an initiliazed instance of valorCtextField component.
     * @return the initialized component instance
     */
    public TextField getValorCtextField() {
        if (valorCtextField == null) {//GEN-END:|26-getter|0|26-preInit
            // write pre-init user code here
            valorCtextField = new TextField("Digite o valor de C:", "", 32, TextField.ANY);//GEN-LINE:|26-getter|1|26-postInit
            // write post-init user code here
        }//GEN-BEGIN:|26-getter|2|
        return valorCtextField;
    }
    //</editor-fold>//GEN-END:|26-getter|2|

    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: CalcularCommand ">//GEN-BEGIN:|29-getter|0|29-preInit
    /**
     * Returns an initiliazed instance of CalcularCommand component.
     * @return the initialized component instance
     */
    public Command getCalcularCommand() {
        if (CalcularCommand == null) {//GEN-END:|29-getter|0|29-preInit
            // write pre-init user code here
            CalcularCommand = new Command("Calcular", Command.ITEM, 0);//GEN-LINE:|29-getter|1|29-postInit
            // write post-init user code here
        }//GEN-BEGIN:|29-getter|2|
        return CalcularCommand;
    }
    //</editor-fold>//GEN-END:|29-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: IrCommand ">//GEN-BEGIN:|38-getter|0|38-preInit
    /**
     * Returns an initiliazed instance of IrCommand component.
     * @return the initialized component instance
     */
    public Command getIrCommand() {
        if (IrCommand == null) {//GEN-END:|38-getter|0|38-preInit
            // write pre-init user code here
            IrCommand = new Command("Ir", Command.BACK, 0);//GEN-LINE:|38-getter|1|38-postInit
            // write post-init user code here
        }//GEN-BEGIN:|38-getter|2|
        return IrCommand;
    }
    //</editor-fold>//GEN-END:|38-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: Logo ">//GEN-BEGIN:|37-getter|0|37-preInit
    /**
     * Returns an initiliazed instance of Logo component.
     * @return the initialized component instance
     */
    public Form getLogo() {
        if (Logo == null) {//GEN-END:|37-getter|0|37-preInit
            // write pre-init user code here
            Logo = new Form("Bh\u00E1skara", new Item[] { getImageItem1() });//GEN-BEGIN:|37-getter|1|37-postInit
            Logo.addCommand(getIrCommand());
            Logo.setCommandListener(this);//GEN-END:|37-getter|1|37-postInit
            // write post-init user code here
        }//GEN-BEGIN:|37-getter|2|
        return Logo;
    }
    //</editor-fold>//GEN-END:|37-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: helpCommand ">//GEN-BEGIN:|48-getter|0|48-preInit
    /**
     * Returns an initiliazed instance of helpCommand component.
     * @return the initialized component instance
     */
    public Command getHelpCommand() {
        if (helpCommand == null) {//GEN-END:|48-getter|0|48-preInit
            // write pre-init user code here
            helpCommand = new Command("Ajuda", Command.HELP, 0);//GEN-LINE:|48-getter|1|48-postInit
            // write post-init user code here
        }//GEN-BEGIN:|48-getter|2|
        return helpCommand;
    }
    //</editor-fold>//GEN-END:|48-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: ProxCommand ">//GEN-BEGIN:|51-getter|0|51-preInit
    /**
     * Returns an initiliazed instance of ProxCommand component.
     * @return the initialized component instance
     */
    public Command getProxCommand() {
        if (ProxCommand == null) {//GEN-END:|51-getter|0|51-preInit
            // write pre-init user code here
            ProxCommand = new Command("Pr\u00F3ximo", Command.BACK, 0);//GEN-LINE:|51-getter|1|51-postInit
            // write post-init user code here
        }//GEN-BEGIN:|51-getter|2|
        return ProxCommand;
    }
    //</editor-fold>//GEN-END:|51-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: Descricaoform ">//GEN-BEGIN:|46-getter|0|46-preInit
    /**
     * Returns an initiliazed instance of Descricaoform component.
     * @return the initialized component instance
     */
    public Form getDescricaoform() {
        if (Descricaoform == null) {//GEN-END:|46-getter|0|46-preInit
            // write pre-init user code here
            Descricaoform = new Form("Descri\u00E7\u00E3o", new Item[] { getStringItem() });//GEN-BEGIN:|46-getter|1|46-postInit
            Descricaoform.addCommand(getProxCommand());
            Descricaoform.setCommandListener(this);//GEN-END:|46-getter|1|46-postInit
            // write post-init user code here
        }//GEN-BEGIN:|46-getter|2|
        return Descricaoform;
    }
    //</editor-fold>//GEN-END:|46-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|56-getter|0|56-preInit
    /**
     * Returns an initiliazed instance of stringItem component.
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|56-getter|0|56-preInit
            // Descrição do que o aplicativo irá fazer.
            stringItem = new StringItem("Pra que serve?", "O Aplicativo serve para calcular a f\u00F3rmula  de Bh\u00E1skara de uma maneira simples, bastando o usu\u00E1rio digitar os valores e o aplicativo mostrar\u00E1 o resultado.");//GEN-LINE:|56-getter|1|56-postInit
            // write post-init user code here
        }//GEN-BEGIN:|56-getter|2|
        return stringItem;
    }
    //</editor-fold>//GEN-END:|56-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: resultadoStringItem ">//GEN-BEGIN:|63-getter|0|63-preInit
    /**
     * Returns an initiliazed instance of resultadoStringItem component.
     * @return the initialized component instance
     */
    public StringItem getResultadoStringItem() {
        if (resultadoStringItem == null) {//GEN-END:|63-getter|0|63-preInit
            // write pre-init user code here
            resultadoStringItem = new StringItem("Resultado:", "");//GEN-LINE:|63-getter|1|63-postInit
            // write post-init user code here
        }//GEN-BEGIN:|63-getter|2|
        return resultadoStringItem;
    }
    //</editor-fold>//GEN-END:|63-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageItem1 ">//GEN-BEGIN:|64-getter|0|64-preInit
    /**
     * Returns an initiliazed instance of imageItem1 component.
     * @return the initialized component instance
     */
    public ImageItem getImageItem1() {
        if (imageItem1 == null) {//GEN-END:|64-getter|0|64-preInit
            // write pre-init user code here
            imageItem1 = new ImageItem("", getBháskara(), ImageItem.LAYOUT_DEFAULT, "<Imagem perdida>");//GEN-LINE:|64-getter|1|64-postInit
            // write post-init user code here
        }//GEN-BEGIN:|64-getter|2|
        return imageItem1;
    }
    //</editor-fold>//GEN-END:|64-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: Bháskara ">//GEN-BEGIN:|65-getter|0|65-preInit
    /**
     * Returns an initiliazed instance of Bháskara component.
     * @return the initialized component instance
     */
    public Image getBháskara() {
        if (Bháskara == null) {//GEN-END:|65-getter|0|65-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|65-getter|1|65-@java.io.IOException
                Bháskara = Image.createImage("/Bhaskara/imagem/Bhaskara.jpg");
            } catch (java.io.IOException e) {//GEN-END:|65-getter|1|65-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|65-getter|2|65-postInit
            // write post-init user code here
        }//GEN-BEGIN:|65-getter|3|
        return Bháskara;
    }
    //</editor-fold>//GEN-END:|65-getter|3|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
    // Criando método para calcular o Delta

    public double delta(double a, double b, double c) {
        double d = (b * b) - (4 * a * c);
        return d;
    }
//Criando método para calcular X1

    public double getX1(double a, double b, double c) {
        return (-b + Math.sqrt(delta(a, b, c))) / (2 * a);
    }
// Criando método que calcula X2

    public double getX2(double a, double b, double c) {
        return (-b - Math.sqrt(delta(a, b, c))) / (2 * a);
    }
// Obtendo resultado

    public void getResultado() {

        if (isValid()) {
            String retorno = "";
            try {
                double a = Double.parseDouble(valorAtextField.getString());
                try {
                    double b = Double.parseDouble(valorBtextField.getString());
                    try {
                        double c = Double.parseDouble(valorCtextField.getString());
                        double x1;
                        double x2;
                        x1 = getX1(a, b, c);
                        x2 = getX2(a, b, c);
                        // Se o resultado não existir mostrar que é inválido.
                        if (Double.isNaN(x1) || Double.isNaN(x2)) {
                            retorno = "Resultado Inválido";
                        } else {
                            retorno = "X1: " + x1;
                            retorno += " e X2: " + x2;
                        }
                        resultadoStringItem.setText(retorno);
                    } catch (Exception e) {
                        resultadoStringItem.setText("Digite apenas números para o valor C");
                    }
                } catch (Exception e) {
                resultadoStringItem.setText("Digite apenas números para o valor B");
                }
            } catch (NumberFormatException e) {
                resultadoStringItem.setText("Digite apenas números para o valor A");
            }


        }
    }
// Método para fazer com que todos os campos sejam digitados

    public boolean isValid() {
        if (valorAtextField == null || valorAtextField.getString().equals("")) {
            resultadoStringItem.setText("Digite o valor de A");
            return false;
        }
        if (valorBtextField == null || valorBtextField.getString().equals("")) {
            resultadoStringItem.setText("Digite o valor de B");
            return false;
        }
        if (valorCtextField == null || valorCtextField.getString().equals("")) {
            resultadoStringItem.setText("Digite o valor de C");
            return false;
        }

        return true;
    }
}
